<template>
  <div class="orders-manage">
    <div class="page-header">
      <h2 class="page-title">订单管理</h2>
      <div class="filter-row">
        <el-select v-model="filterStatus" placeholder="订单状态" clearable @change="handleFilterChange">
          <el-option
            v-for="item in orderStatuses"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </div>
    </div>

    <el-table :data="orders" style="width: 100%" v-loading="loading">
      <el-table-column prop="id" label="订单号" width="180" />
      <el-table-column prop="userId" label="用户ID" width="100" />
      <el-table-column prop="createTime" label="下单时间" width="180">
        <template #default="{ row }">
          {{ new Date(row.createTime).toLocaleString() }}
        </template>
      </el-table-column>
      <el-table-column prop="totalAmount" label="订单金额">
        <template #default="{ row }">
          ¥{{ (row.totalAmount !== undefined && row.totalAmount !== null) ? row.totalAmount.toFixed(2) : '0.00' }}
        </template>
      </el-table-column>
      <el-table-column prop="status" label="状态" width="120">
        <template #default="{ row }">
          <el-tag :type="getStatusType(row.status)">
            {{ getStatusLabel(row.status) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="200">
        <template #default="{ row }">
          <el-button-group>
            <el-button 
              type="primary" 
              size="small" 
              @click="handleViewDetails(row)"
            >
              <el-icon><View /></el-icon>
            </el-button>
            <el-button 
              type="success" 
              size="small" 
              @click="handleUpdateStatus(row)"
              :disabled="!canUpdateStatus(row.status)"
            >
              <el-icon><Check /></el-icon>
            </el-button>
          </el-button-group>
        </template>
      </el-table-column>
    </el-table>

    <!-- 订单详情对话框 -->
    <el-dialog
      title="订单详情"
      v-model="detailsVisible"
      width="600px"
    >
      <template v-if="currentOrder">
        <div class="order-info">
          <div class="info-item">
            <span class="label">订单号：</span>
            <span>{{ currentOrder.id }}</span>
          </div>
          <div class="info-item">
            <span class="label">下单时间：</span>
            <span>{{ new Date(currentOrder.createTime).toLocaleString() }}</span>
          </div>
          <div class="info-item">
            <span class="label">订单状态：</span>
            <el-tag :type="getStatusType(currentOrder.status)">
              {{ getStatusLabel(currentOrder.status) }}
            </el-tag>
          </div>
          <div class="info-item">
            <span class="label">收货人：</span>
            <span>{{ currentOrder.shippingAddress.name }}</span>
          </div>
          <div class="info-item">
            <span class="label">联系电话：</span>
            <span>{{ currentOrder.shippingAddress.phone }}</span>
          </div>
          <div class="info-item">
            <span class="label">收货地址：</span>
            <span>{{ currentOrder.shippingAddress.address }}</span>
          </div>
        </div>

        <el-divider>订单商品</el-divider>

        <el-table :data="currentOrder.items" style="width: 100%">
          <el-table-column prop="name" label="商品名称" />
          <el-table-column prop="price" label="单价">
            <template #default="{ row }">
              ¥{{ row.price.toFixed(2) }}
            </template>
          </el-table-column>
          <el-table-column prop="quantity" label="数量" width="100" />
          <el-table-column label="小计">
            <template #default="{ row }">
              ¥{{ (row.price * row.quantity).toFixed(2) }}
            </template>
          </el-table-column>
        </el-table>

        <div class="order-total">
          <span class="label">订单总额：</span>
          <span class="amount">¥{{ currentOrder.totalAmount.toFixed(2) }}</span>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, onMounted } from 'vue'
import { View, Check } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import axios from 'axios'

export default {
  name: 'OrdersManage',
  components: {
    View,
    Check
  },
  setup() {
    const orders = ref([])
    const loading = ref(false)
    const detailsVisible = ref(false)
    const currentOrder = ref(null)
    const filterStatus = ref('')

    const orderStatuses = [
      { value: 'pending', label: '待付款' },
      { value: 'paid', label: '已付款' },
      { value: 'shipping', label: '配送中' },
      { value: 'completed', label: '已完成' },
      { value: 'cancelled', label: '已取消' }
    ]

    const getStatusType = (status) => {
      const types = {
        pending: 'warning',
        paid: 'primary',
        shipping: 'info',
        completed: 'success',
        cancelled: 'danger'
      }
      return types[status] || 'info'
    }

    const getStatusLabel = (status) => {
      const labels = {
        pending: '待付款',
        paid: '已付款',
        shipping: '配送中',
        completed: '已完成',
        cancelled: '已取消'
      }
      return labels[status] || status
    }

    const canUpdateStatus = (status) => {
      return ['paid', 'shipping'].includes(status)
    }

    const fetchOrders = async () => {
      loading.value = true
      try {
        const params = filterStatus.value ? { status: filterStatus.value } : {}
        const response = await axios.get('http://localhost:3000/orders', { params })
        orders.value = response.data.map(order => ({
          ...order,
          createTime: order.createdAt,
          totalAmount: order.total
        }))
      } catch (error) {
        ElMessage.error('获取订单列表失败')
      } finally {
        loading.value = false
      }
    }

    const handleViewDetails = async (row) => {
      try {
        const response = await axios.get(`http://localhost:3000/orders/${row.id}`)
        const order = response.data
        currentOrder.value = {
          ...order,
          createTime: order.createdAt,
          totalAmount: order.total
        }
        detailsVisible.value = true
      } catch (error) {
        ElMessage.error('获取订单详情失败')
      }
    }

    const handleUpdateStatus = (row) => {
      const nextStatus = row.status === 'paid' ? 'shipping' : 'completed'
      const statusLabel = getStatusLabel(nextStatus)

      ElMessageBox.confirm(
        `确定将订单状态更新为"${statusLabel}"吗？`,
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).then(async () => {
        try {
          await axios.patch(`http://localhost:3000/orders/${row.id}`, {
            status: nextStatus
          })
          ElMessage.success('状态更新成功')
          fetchOrders()
        } catch (error) {
          ElMessage.error('状态更新失败')
        }
      })
    }

    const handleFilterChange = () => {
      fetchOrders()
    }

    onMounted(() => {
      console.log('订单管理页面加载')
      fetchOrders()
    })

    return {
      orders,
      loading,
      detailsVisible,
      currentOrder,
      filterStatus,
      orderStatuses,
      getStatusType,
      getStatusLabel,
      canUpdateStatus,
      handleViewDetails,
      handleUpdateStatus,
      handleFilterChange
    }
  }
}
</script>

<style scoped>
.orders-manage {
  padding: 20px;
}

.page-header {
  display: flex;
  flex-direction: column;
  align-items: flex-start;
  margin-bottom: 20px;
}

.page-title {
  margin-bottom: 10px;
}

.filter-row {
  width: 100%;
  display: flex;
  justify-content: flex-start;
}

.order-info {
  margin-bottom: 20px;
}

.info-item {
  margin-bottom: 10px;
  display: flex;
  align-items: center;
}

.info-item .label {
  width: 100px;
  color: #606266;
}

.order-total {
  margin-top: 20px;
  text-align: right;
  font-size: 16px;
}

.order-total .label {
  color: #606266;
  margin-right: 10px;
}

.order-total .amount {
  color: #f56c6c;
  font-weight: bold;
}
</style> 